package com.sure.supermarketserver.branch.staff.impl;

import com.sure.supermarketserver.branch.staff.StaffDto;
import com.sure.supermarketserver.branch.staff.StaffService;
import com.sure.supermarketserver.branch.staff.dao.StaffDao;
import com.sure.supermarketserver.common.Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service//说明这是一个受spring容器管理的业务组件(Bean)
@Transactional//本类方法均为事务性的
public class StaffServiceImpl implements StaffService {

    @Resource
    private StaffDao staffDao;

    @Override
    public boolean checkStaffList(String userId) {
        int cnt = staffDao.checkByUserId(userId);
        return cnt > 0;
    }

    @Override
    public Map<String, Object> getStaffList(StaffDto dto, String userId) {
        return Utils.getPage(dto, () -> staffDao.findStaffList(dto, userId));
    }

    @Override
    public Map<String, Object> getAllStaffList(StaffDto dto) {
        return Utils.getPage(dto, () -> staffDao.findAllStaffList(dto));

    }

    @Override
    public void addStaff(StaffDto dto, String userId) {
        dto.setSt_entry(new Date());
        try {
            boolean hasStaff = staffDao.findStaff(dto.getSt_id());
            if (hasStaff) {
                throw new RuntimeException("该员工号已被占用，换一个试试吧！");
            }
            staffDao.insertStaff(userId);
            staffDao.updateStaff(dto);
            staffDao.insertRole(dto);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("添加员工失败！", e);
        }
    }

    @Override
    public void delStaff(String id) {
        try {
            staffDao.delRole(id);
            staffDao.delStaff(id);
        } catch (Exception e) {
            throw new RuntimeException("删除员工失败！", e);
        }
    }

    @Override
    public void updStaff(StaffDto dto) {
        staffDao.updStaff(dto);
        staffDao.updRole(dto);
    }

}
